//
//  LoadingPopView.m
//  Refresh
//
//  Created by ning liu on 2018/3/15.
//  Copyright © 2018年 ning liu. All rights reserved.
//

#import "LoadingPopView.h"

@interface LoadingPopView ()

@property (strong, nonatomic) CAShapeLayer * ringShapeLayer;

@end

@implementation LoadingPopView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self buildView];
    }
    
    return self;
}

-(void)buildView
{
    self.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.7];
    self.layer.cornerRadius = 10;
    
    //虚线圆环
    self.ringShapeLayer.frame = CGRectMake(0, 0, 78, 78);
    self.ringShapeLayer.position = CGPointMake(self.frame.size.width/2.0f, self.frame.size.height/2.0f-18);
    [self.layer addSublayer:self.ringShapeLayer];
    
    UIBezierPath *bezierPath =[UIBezierPath bezierPathWithRoundedRect:self.ringShapeLayer.bounds cornerRadius:self.ringShapeLayer.frame.size.width/2.];
    self.ringShapeLayer.path = bezierPath.CGPath;
    
    
    //icon
    UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
    icon.image = [UIImage imageNamed:@"refresh_icon"];
    icon.center = self.ringShapeLayer.position;
    [self addSubview:icon];
    
    UILabel *msglabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.ringShapeLayer.frame.size.height+self.ringShapeLayer.frame.origin.y+11, self.frame.size.width, 25)];
    msglabel.font = [UIFont systemFontOfSize:15.0f];
    msglabel.textColor = [UIColor whiteColor];
    msglabel.textAlignment = NSTextAlignmentCenter;
    msglabel.text = @"加载中";
    [self addSubview:msglabel];
    
    //旋转
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(0.0);
    animation.toValue = @(2*M_PI);
    animation.duration = 0.8;
    animation.repeatCount = INFINITY;
    animation.removedOnCompletion = NO;
    [self.ringShapeLayer addAnimation:animation forKey:animation.keyPath];
}

-(void)stopLoading
{
    [self.ringShapeLayer removeAllAnimations];
}

-(void)removeFromSuperview
{
    [self stopLoading];
    [super removeFromSuperview];
}

- (CAShapeLayer *)ringShapeLayer{
    if (!_ringShapeLayer) {
        _ringShapeLayer = [CAShapeLayer layer];
        _ringShapeLayer.lineWidth = 3;
        _ringShapeLayer.backgroundColor = [UIColor clearColor].CGColor;
        _ringShapeLayer.fillColor = [UIColor clearColor].CGColor;
        _ringShapeLayer.strokeColor = [UIColor whiteColor].CGColor;
        [_ringShapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithFloat:1], [NSNumber numberWithFloat:3], nil]];
        _ringShapeLayer.strokeEnd = 1;
    }
    return _ringShapeLayer;
}
@end
